

// 添加调试函数
function debug(message) {
    console.log(`Debug: ${message}`);
}

// 等待 DOM 加载完成
document.addEventListener('DOMContentLoaded', () => {
    debug('DOM loaded');
    
    // 获取按钮元素
    const loginBtn = document.getElementById('loginBtn');
    const showRegisterBtn = document.getElementById('showRegisterBtn');
    const sendMessageBtn = document.getElementById('sendMessageBtn');
    
    debug('Login button: ' + (loginBtn ? 'found' : 'not found'));
    debug('Register button: ' + (showRegisterBtn ? 'found' : 'not found'));
    
    // 绑定事件监听器
    if (loginBtn) {
        loginBtn.addEventListener('click', () => {
            debug('Login button clicked');
            login();
        });
    }
    
    if (showRegisterBtn) {
        showRegisterBtn.addEventListener('click', () => {
            debug('Register button clicked');
            showRegister();
        });
    }
    
    if (sendMessageBtn) {
        sendMessageBtn.addEventListener('click', () => {
            debug('Send button clicked');
            sendMessage();
        });
    }
});

// 登录功能
async function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (!username || !password) {
        alert('请输入用户名和密码');
        return;
    }

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();
        if (data.success) {
            // 保存用户信息到本地存储
            localStorage.setItem('currentUser', JSON.stringify(data.user));
            document.getElementById('loginForm').style.display = 'none';
            document.getElementById('chatContainer').style.display = 'flex';
            loadOnlineUsers();
            // 定时刷新在线用户列表
            setInterval(loadOnlineUsers, 5000);
        } else {
            alert('登录失败：' + data.message);
        }
    } catch (error) {
        console.error('登录错误：', error);
        alert('登录失败，请稍后重试');
    }
}

// 加载在线用户列表
async function loadOnlineUsers() {
    try {
        const response = await fetch('/api/online-users');
        const data = await response.json();
        
        if (data.success) {
            const onlineUsersDiv = document.getElementById('onlineUsers');
            onlineUsersDiv.innerHTML = '';
            
            const currentUser = JSON.parse(localStorage.getItem('currentUser'));
            
            data.users.forEach(user => {
                if (user.user_id !== currentUser.user_id) {
                    const userElement = document.createElement('div');
                    userElement.className = 'online-user';
                    userElement.innerHTML = `
                        <span class="user-name">${user.username}</span>
                        <span class="online-status">●</span>
                    `;
                    // 添加右键点击事件
                    userElement.addEventListener('contextmenu', async (e) => {
                        e.preventDefault();
                        showUserCard(user.user_id, e.clientX, e.clientY);
                    });
                    // 添加左键点击事件
                    userElement.addEventListener('click', () => startChat(user));
                    onlineUsersDiv.appendChild(userElement);
                }
            });
        }
    } catch (error) {
        console.error('加载在线用户失败：', error);
    }
}

// 开始与用户聊天
async function startChat(user) {
    const messageArea = document.getElementById('messageArea');
    messageArea.innerHTML = `
        <div class="chat-header">
            <div class="chat-header-title">正在与 ${user.username} 聊天</div>
           
        </div>
    `;
    localStorage.setItem('currentChatUser', JSON.stringify(user));
    
    // 加载历史消息
    await loadChatHistory(user.user_id);
}

// 加载聊天历史
async function loadChatHistory(userId) {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    try {
        const response = await fetch(`/api/messages/${userId}?currentUser=${currentUser.user_id}`);
        const data = await response.json();
        
        if (data.success) {
            const messageArea = document.getElementById('messageArea');
            // 保留聊天标题
            const chatHeader = messageArea.querySelector('.chat-header');
            messageArea.innerHTML = '';
            messageArea.appendChild(chatHeader);
            
            // 添加刷新按钮
            addRefreshButton();
            
            // 使用Set记录已显示的消息ID
            const displayedMessageIds = new Set();
            
            // 只显示未删除且未显示过的消息
            data.messages.forEach(msg => {
                if (!msg.deleted && !displayedMessageIds.has(msg.message_id.toString())) {
                    displayedMessageIds.add(msg.message_id.toString());
                    appendMessage(msg.content, msg.sender_id === currentUser.user_id, msg.send_time, msg.message_id, msg.status);
                }
            });
        }
    } catch (error) {
        console.error('加载聊天历史失败：', error);
    }
}

// 检查新消息
async function checkNewMessages(userId) {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const lastMessage = document.querySelector('#messageArea .message:last-child');
    const lastMessageTime = lastMessage ? lastMessage.dataset.time : '1970-01-01';

    try {
        const response = await fetch(`/api/new-messages/${userId}?currentUser=${currentUser.user_id}&lastTime=${lastMessageTime}`);
        const data = await response.json();
        
        if (data.success && data.messages.length > 0) {
            // 获取已显示的消息ID集合
            const displayedMessageIds = new Set(
                Array.from(document.querySelectorAll('.message'))
                    .map(el => el.dataset.messageId)
            );

            // 只显示未显示过的消息
            data.messages.forEach(msg => {
                if (!displayedMessageIds.has(msg.message_id.toString())) {
                    const isSent = msg.sender_id === currentUser.user_id;
                    appendMessage(msg.content, isSent, msg.send_time, msg.message_id, msg.status);
                }
            });
        }
    } catch (error) {
        console.error('检查新消息失败：', error);
    }
}

// 显示注册表单
function showRegister() {
    const loginForm = document.getElementById('loginForm');
    loginForm.innerHTML = `
      
        <h2>注册新用户</h2>
        <div class="input-group">
            <i class="fas fa-user"></i>
            <input type="text" id="regUsername" placeholder="用户名">
        </div>
        <div class="input-group">
            <i class="fas fa-lock"></i>
            <input type="password" id="regPassword" placeholder="密码">
        </div>
        <div class="input-group">
            <i class="fas fa-envelope"></i>
            <input type="email" id="regEmail" placeholder="电子邮箱">
        </div>
        <div class="input-group">
            <i class="fab fa-qq"></i>
            <input type="text" id="regQQ" placeholder="QQ号码（选填）">
        </div>
        <div class="input-group">
            <i class="fas fa-phone"></i>
            <input type="text" id="regPhone" placeholder="手机号码（选填）">
        </div>
        <button onclick="register()">注 册</button>
        <button onclick="showLogin()">返回登录</button>
    `;
}

// 显示登录表单
function showLogin() {
    const loginForm = document.getElementById('loginForm');
    loginForm.innerHTML = `
        <div class="author-info">
            <h1>即时通讯系统</h1>
            <p>作者：知识星球L站</p>
        </div>
        <h2>欢迎登录</h2>
        <div class="input-group">
            <i class="fas fa-user"></i>
            <input type="text" id="username" placeholder="用户名">
        </div>
        <div class="input-group">
            <i class="fas fa-lock"></i>
            <input type="password" id="password" placeholder="密码">
        </div>
        <button onclick="login()">登 录</button>
        <button onclick="showRegister()">注册新用户</button>
    `;
}

// 注册功能
async function register() {
    const username = document.getElementById('regUsername').value;
    const password = document.getElementById('regPassword').value;
    const email = document.getElementById('regEmail').value;
    const qq_number = document.getElementById('regQQ').value;
    const phone_number = document.getElementById('regPhone').value;

    if (!username || !password || !email) {
        alert('请填写必填项（用户名、密码、邮箱）');
        return;
    }

    // 验证QQ号格式
    if (qq_number && !/^\d{5,11}$/.test(qq_number)) {
        alert('QQ号格式不正确');
        return;
    }

    // 验证手机号格式
    if (phone_number && !/^1[3-9]\d{9}$/.test(phone_number)) {
        alert('手机号格式不正确');
        return;
    }

    try {
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username,
                password,
                email,
                qq_number,
                phone_number
            })
        });

        const data = await response.json();
        if (data.success) {
            alert('注册成功！');
            showLogin();
        } else {
            alert('注册失败：' + data.message);
        }
    } catch (error) {
        console.error('注册错误：', error);
        alert('注册失败，请稍后重试');
    }
}

// 发送消息
async function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const currentChatUser = JSON.parse(localStorage.getItem('currentChatUser'));

    if (!currentChatUser) {
        alert('请先选择聊天对象');
        return;
    }

    if (message) {
        try {
            const response = await fetch('/api/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    sender_id: currentUser.user_id,
                    receiver_id: currentChatUser.user_id,
                    content: message
                })
            });

            const data = await response.json();
            if (data.success) {
                // 检查消息是否已经显示
                const existingMessage = document.querySelector(`.message[data-message-id="${data.messageId}"]`);
                if (!existingMessage) {
                    appendMessage(message, true, data.send_time, data.messageId);
                }
                messageInput.value = '';
            } else {
                alert('发送失败：' + data.message);
            }
        } catch (error) {
            console.error('发送消息失败：', error);
            alert('发送失败，请重试');
        }
    }
}

// 显示消息
function appendMessage(message, isSent = false, timestamp = null, messageId = null, status = 'normal', deleted = false) {
    const messageArea = document.getElementById('messageArea');
    const messageElement = document.createElement('div');
    messageElement.className = `message ${isSent ? 'sent' : 'received'}`;
    if (status === 'recalled') {
        messageElement.classList.add('recalled');
    }
    if (deleted) {
        messageElement.classList.add('deleted');
    }
    messageElement.dataset.messageId = messageId;
    
    const messageContent = document.createElement('div');
    messageContent.className = 'message-content';
    messageContent.textContent = deleted ? '此消息已删除' : 
                               status === 'recalled' ? '此消息已撤回' : 
                               message;
    messageElement.appendChild(messageContent);
    
    // 只显示删除按钮
    if (isSent && !deleted && status === 'normal' && messageId) {
        const messageActions = document.createElement('div');
        messageActions.className = 'message-actions';
        messageActions.innerHTML = `
            <button class="delete-btn" onclick="deleteMessage('${messageId}')">
                <i class="fas fa-trash"></i> 撤回
            </button>
        `;
        messageElement.appendChild(messageActions);
    }
    
    if (timestamp) {
        messageElement.dataset.time = timestamp;
        const timeElement = document.createElement('div');
        timeElement.className = 'message-time';
        timeElement.textContent = new Date(timestamp).toLocaleTimeString();
        messageElement.appendChild(timeElement);
    }
    
    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}

// 添加消息提示音功能（可选）
function playMessageSound() {
    const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBkCY2e/GdSgFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBTqP0+3LfC8GHm7A7+OZSA0PVqzn77BdGAg+ltbuy3svBzGH18PXlUwMC1Opg4mRlpugoaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW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i4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==');
    audio.play().catch(e => console.log('无法播放提示音'));
}

// 确保函数在全局作用域可用
window.login = login;
window.showRegister = showRegister;
window.showLogin = showLogin;
window.register = register;
window.sendMessage = sendMessage;

// 添加手动刷新按钮的处理函数
function addRefreshButton() {
    const chatHeader = document.querySelector('.chat-header');
    if (chatHeader) {
        const refreshButton = document.createElement('button');
        refreshButton.className = 'refresh-button';
        refreshButton.innerHTML = '刷新消息';
        refreshButton.onclick = () => {
            const currentChatUser = JSON.parse(localStorage.getItem('currentChatUser'));
            if (currentChatUser) {
                checkNewMessages(currentChatUser.user_id);
            }
        };
        chatHeader.appendChild(refreshButton);
    }
}

// 添加显示用户信息卡函数
async function showUserCard(userId, x, y) {
    try {
        const response = await fetch(`/api/user-info/${userId}`);
        const data = await response.json();
        
        if (data.success) {
            // 移除已存在的用户卡片
            const existingCard = document.querySelector('.user-card');
            if (existingCard) {
                existingCard.remove();
            }
            
            const userCard = document.createElement('div');
            userCard.className = 'user-card';
            userCard.innerHTML = `
                <div class="user-card-header">
                    <h3>用户信息</h3>
                    <button class="close-card">×</button>
                </div>
                <div class="user-card-content">
                    <div class="info-item">
                        <span class="info-label">用户名：</span>
                        <span class="info-value">${data.user.username}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">邮箱：</span>
                        <span class="info-value">${data.user.email}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">QQ：</span>
                        <span class="info-value">${data.user.qq_number || '未设置'}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">手机：</span>
                        <span class="info-value">${data.user.phone_number || '未设置'}</span>
                    </div>
                </div>
            `;
            
            // 计算位置，确保卡片不会超出视窗
            const windowWidth = window.innerWidth;
            const windowHeight = window.innerHeight;
            const cardWidth = 300; // 卡片宽度
            const cardHeight = 250; // 预估卡片高度

            // 调整 x 坐标，确保不超出右边界
            let posX = x + 10; // 在击位置右侧10px处显示
            if (posX + cardWidth > windowWidth) {
                posX = x - cardWidth - 10; // 如果超出右边界，则显示在左侧
            }

            // 调整 y 坐标，确保不超出下边界
            let posY = y + 10;
            if (posY + cardHeight > windowHeight) {
                posY = windowHeight - cardHeight - 10;
            }

            userCard.style.left = `${posX}px`;
            userCard.style.top = `${posY}px`;
            
            // 添加关闭按钮事件
            document.body.appendChild(userCard);
            userCard.querySelector('.close-card').onclick = () => userCard.remove();
            
            // 点击其他地方关闭卡片
            document.addEventListener('click', function closeCard(e) {
                if (!userCard.contains(e.target)) {
                    userCard.remove();
                    document.removeEventListener('click', closeCard);
                }
            });
        }
    } catch (error) {
        console.error('获取用户信息失败：', error);
    }
}

// 添加侧边栏折叠功能
function toggleSidebar() {
    const sidebar = document.querySelector('.chat-sidebar');
    sidebar.classList.toggle('collapsed');
    
    // 保存状态到本地存储
    localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed'));
    
    // 更新按钮图标方向
    const toggleBtn = document.querySelector('.toggle-sidebar i');
    if (sidebar.classList.contains('collapsed')) {
        toggleBtn.className = 'fas fa-chevron-right';
    } else {
        toggleBtn.className = 'fas fa-chevron-left';
    }
}

// 页面加载时恢复侧边栏状态
document.addEventListener('DOMContentLoaded', () => {
    const sidebar = document.querySelector('.chat-sidebar');
    const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    
    if (isCollapsed) {
        sidebar.classList.add('collapsed');
        document.querySelector('.toggle-sidebar i').className = 'fas fa-chevron-right';
    }
});

// 确保函数在全局作用域可用
window.toggleSidebar = toggleSidebar;

// 添加撤回消息功能
async function recallMessage(messageId) {
    try {
        if (!messageId) {
            console.error('消息ID不存在');
            return;
        }

        const response = await fetch(`/api/messages/${messageId}/recall`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.message || '撤回失败');
        }

        if (data.success) {
            // 找到对应的消息元素并修改显示
            const messageElement = document.querySelector(`.message[data-message-id="${messageId}"]`);
            if (messageElement) {
                messageElement.querySelector('.message-content').textContent = '此消息已撤回';
                messageElement.classList.add('recalled');
                // 移除撤回按钮
                const actionBtn = messageElement.querySelector('.message-actions');
                if (actionBtn) {
                    actionBtn.remove();
                }
            }
        } else {
            throw new Error(data.message || '撤回失败');
        }
    } catch (error) {
        console.error('撤回消息失败：', error);
        alert(error.message || '撤回失败，请重试');
    }
}

// 确保函数在全局作用域可用
window.recallMessage = recallMessage;

// 添加删除消息功能
async function deleteMessage(messageId) {
    try {
        if (!messageId) {
            console.error('消息ID不存在');
            return;
        }

        if (!confirm('确定要撤回这条消息吗？撤回后不可恢复。')) {
            return;
        }

        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (!currentUser) {
            throw new Error('用户未登录');
        }

        console.log('尝试删除消息:', messageId);

        const response = await fetch(`/api/messages/${messageId}/delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                currentUser: {
                    user_id: currentUser.user_id,
                    username: currentUser.username
                }
            })
        });

        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.message || `删除失败 (${response.status})`);
        }

        if (data.success) {
            // 找到对应的消息元素并直接移除
            const messageElement = document.querySelector(`.message[data-message-id="${messageId}"]`);
            if (messageElement) {
                messageElement.remove(); // 直接从DOM中移除消息元素
            }
        } else {
            throw new Error(data.message || '删除失败');
        }
    } catch (error) {
        console.error('删除消息失败：', error);
        alert(error.message || '删除失败，请重试');
    }
}

// 确保函数在全局作用域可用
window.deleteMessage = deleteMessage;

// 添加退出登录功能
async function logout() {
    try {
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (!currentUser) {
            alert('用户未登录');
            return;
        }

        if (!confirm('确定要退出登录吗？')) {
            return;
        }

        const response = await fetch('/api/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_id: currentUser.user_id
            })
        });

        const data = await response.json();
        if (data.success) {
            // 清除本地存储
            localStorage.removeItem('currentUser');
            localStorage.removeItem('currentChatUser');
            
            // 隐藏聊天界面，显示登录界面
            document.getElementById('chatContainer').style.display = 'none';
            document.getElementById('loginForm').style.display = 'block';
            
            // 清空聊天区域和用户列表
            document.getElementById('messageArea').innerHTML = '';
            document.getElementById('onlineUsers').innerHTML = '';
            
            // 重置登录表单
            const loginForm = document.getElementById('loginForm');
            loginForm.innerHTML = `
                <div class="author-info">
                    <h1>在线交友</h1>
                </div>
                <div class="input-group">
                    <i class="fas fa-user"></i>
                    <input type="text" id="username" placeholder="用户名">
                </div>
                <div class="input-group">
                    <i class="fas fa-lock"></i>
                    <input type="password" id="password" placeholder="密码">
                </div>
                <button onclick="login()">登 录</button>
                <button onclick="showRegister()">注册新用户</button>
            `;
        } else {
            throw new Error(data.message || '退出失败');
        }
    } catch (error) {
        console.error('退出登录失败：', error);
        alert(error.message || '退出失败，请重试');
    }
}

// 确保函数在全局作用域可用
window.logout = logout;
console.log(`
================================
在线交友
作者：知识星球L站
版本：1.0.0
================================
`);